package org.chenqiang.cqlib.dbf;

import java.io.OutputStream;
import java.util.Collection;
import java.util.Date;

import com.linuxense.javadbf.DBFException;
import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFWriter;

/**
 * The abstract class of file in DBF format.
 * @author CHEN Qiang
 *
 * @param <T>
 */
public abstract class DBFFile<T> {
	public static DBFField createDBFField(byte dataType, String name, int length, int decimalCount) {
		DBFField field = new DBFField();
		field.setName(name);
		field.setDataType(dataType);
		field.setFieldLength(length);
		field.setDecimalCount(decimalCount);
		return field;
	}
	
	public abstract Object [] getValues(T item, DBFField [] field);
	
	public abstract DBFField [] getFields();
	
	public static Object getNullValue(DBFField field) {
		switch(field.getDataType()) {
		case DBFField.FIELD_TYPE_C:
			return "";
		case DBFField.FIELD_TYPE_D:
			return new Date();
		case DBFField.FIELD_TYPE_F:
			return Double.valueOf(0);
		case DBFField.FIELD_TYPE_L:
			return Boolean.valueOf(false);
		case DBFField.FIELD_TYPE_N:
			return Double.valueOf(0);
		case DBFField.FIELD_TYPE_M:
			return "";
		default:
			return "";
		}
	}
	
	public void process(Collection<T> data, String encoding, OutputStream os) throws DBFException {
		DBFWriter writer = new DBFWriter();
		writer.setCharactersetName(encoding);
		
		DBFField [] fields = this.getFields();
		writer.setFields(fields);		
		
		for(T item : data) {
			writer.addRecord(this.getValues(item, fields));
		}
		writer.write(os);
	}
}
